package ACWing.SearchAndGraphTheory.BFS;
//844 走迷宫

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;

/**
 * @author :chenjie
 * @date :Created 2022/12/15 18:42
 */
public class WalkTGHEMaze {
    static class Pall{
        int x;
        int y;

        public Pall(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return "Pall{" +
                    "x=" + x +
                    ", y=" + y +
                    '}';
        }
    }
    static Pall[][]palls=new Pall[110][110];//记录路径
    static Queue<Pall> queue=new ArrayDeque<>();
    static int[][]d=new int[110][110];
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int m=sc.nextInt();
        int[][]arr=new int[n][m];
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j]=sc.nextInt();
            }
        }
        //初始化距离-1为未被访问过
        for (int i = 0; i <n; i++) {
            for (int j = 0; j < m; j++) {
                d[i][j]=-1;
            }
        }
        System.out.println(bfs(n, m, arr));
        int x=n-1,y=m-1;
        while (x!=0||y!=0){
            System.out.println(x+" "+y);
            x=palls[x][y].x;
            y=palls[x][y].y;
        }

    }
    public static int bfs(int n,int m,int[][]arr){
        queue.add(new Pall(0,0));
        palls[0][0]=new Pall(0,0);
        d[0][0]=0;
        //扩展元素的坐标上下左右（新奇点直接省略4个if）
        int[]dx={-1,0,1,0};
        int[]dy={0,1,0,-1};
        while (queue.size()>0){
            Pall t=queue.poll();
            for (int i = 0; i < 4; i++) {
                int x=t.x+dx[i],y=t.y+dy[i];
                if(x>=0&&x<n&&y>=0&&y<m&&d[x][y]==-1&&arr[x][y]==0){
                    d[x][y]=d[t.x][t.y]+1;
                    palls[x][y]=t;
                    queue.add(new Pall(x,y));
                    
                }
            }
        }
        return d[n-1][m-1];
    }
}
